﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CanDoo;
using CanDoo.Core;
using CanDoo.Core.Data;
using CanDoo.Data;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.Core.DTOs;

namespace CanDoo.Oil.Core.Services
{
    /// <summary>
    /// 业务实现——采购结算单
    /// </summary>
    public class BuyStatementService : CanDoo.Data.Entity.Services.ServiceBase<BuyStatement>, IBuyStatementContract
    {
        public BuyStatementService()
        {
        
        }

        public string GetNewCode()
        {
            var startStr = "YFJS";
            var dateStr = DateTime.Now.ToString("yyMMdd");
            var codePrefix = startStr + dateStr;

            //生成新单据号
            var newCode = "";
            var entity = Entities.Where(p => p.Code.StartsWith(codePrefix)).OrderByDescending(p => p.Code).FirstOrDefault();
            if (entity == null)
                newCode = codePrefix + "0001";
            else
                newCode = startStr + (int.Parse(entity.Code.Substring(startStr.Length)) + 1);
            return newCode;
        }

        public override OperationResult PassEntity(long entityId)
        {
            //1、修改记录的审核状态
            //2、修改关联单据的支付状态，支付金额，待支付金额
            //3、如果使用到了预付款，修改预付款的使用状态，使用金额，待使用金额
            var entity = new BuyStatement();

            using (var scope = DbScopeFactory.Create())
            {
                entity = GetById(entityId);
                if (entity.PassState == PassState.Pass || entity.PassState == PassState.UnPass)
                    return new OperationResult(OperationResultType.Error, "此数据已通过审核");

                base.PassEntity(entityId);

                foreach (var m in entity.BuyStatementDetails)
                {
                    if (m.BeforeMoney != m.BuyBill.WaitMoney)
                        throw new Exception("单据[" + m.BuyBill.Code + "]在添加结算单后调整过待支付金额");
                    else
                    {
                        if (m.BuyBill.Money > 0)//支付的单据
                        {
                            if(m.Money<0)
                                throw new Exception("单据[" + m.BuyBill.Code + "]的支付金额应大于0");

                            m.BuyBill.PayedMoney = m.BuyBill.PayedMoney + m.Money;
                            m.BuyBill.WaitMoney = m.LastedMoney;

                            if (m.BuyBill.WaitMoney == 0)
                                m.BuyBill.PayState = PayStateEnum.AllPayed;
                            else if (m.BuyBill.WaitMoney>0)
                                m.BuyBill.PayState = PayStateEnum.HalfPayed;
                            else
                                throw new Exception("单据[" + m.BuyBill.Code + "]的金额超过应支付的总金额");
                        }
                        else//退货的单据
                        {
                            if (m.Money > 0)
                                throw new Exception("单据[" + m.BuyBill.Code + "]的支付金额应小于0");

                            m.BuyBill.PayedMoney = m.BuyBill.PayedMoney + m.Money;
                            m.BuyBill.WaitMoney = m.LastedMoney;

                            if (m.BuyBill.WaitMoney == 0)
                                m.BuyBill.PayState = PayStateEnum.AllPayed;
                            else if (m.BuyBill.WaitMoney < 0)
                                m.BuyBill.PayState = PayStateEnum.HalfPayed;
                            else
                                throw new Exception("单据[" + m.BuyBill.Code + "]的金额超过应支付的总金额");
                        }
                    }
                }

                if (entity.BuyAdvanceMoney != null)
                {
                    var advanceLasted = entity.BuyAdvanceMoney.Money - entity.BuyAdvanceMoney.UsedMoney;
                    if (entity.AdvanceMoney > advanceLasted)
                        throw new Exception("使用的预付款金额超过预付款余额");
                    else
                        entity.BuyAdvanceMoney.UsedMoney = advanceLasted - entity.AdvanceMoney;
                }

                Update(entity);

                
                return scope.SaveChanges()>0? new OperationResult(OperationResultType.Success, $"审核通过1条记录!") : new OperationResult(OperationResultType.NoChanged);
            }
        }

        public override OperationResult UnPassEntity(long entityId)
        {
            var entity = new BuyStatement();

            using (var scope = DbScopeFactory.Create())
            {
                entity = GetById(entityId);
                if (entity.PassState == PassState.UnPass || entity.PassState == PassState.Wait)
                    return new OperationResult(OperationResultType.Error, "此数据未通过审核");

                base.UnPassEntity(entityId);

                foreach (var m in entity.BuyStatementDetails)
                {
                    if (m.BuyBill.Money > 0)//支付的单据
                    {
                        m.BuyBill.PayedMoney = m.BuyBill.PayedMoney - m.Money;
                        m.BuyBill.WaitMoney = m.BuyBill.WaitMoney + m.Money;

                        if (m.BuyBill.PayedMoney == 0)
                            m.BuyBill.PayState = PayStateEnum.NoPayed;
                        else if (m.BuyBill.WaitMoney > 0 && m.BuyBill.PayedMoney > 0)
                            m.BuyBill.PayState = PayStateEnum.HalfPayed;
                        else
                            throw new Exception("单据[" + m.BuyBill.Code + "]的金额超过应支付的总金额");
                    }
                    else//退货的单据
                    {
                        if (m.Money > 0)
                            throw new Exception("单据[" + m.BuyBill.Code + "]的支付金额应小于0");

                        m.BuyBill.PayedMoney = m.BuyBill.PayedMoney - m.Money;
                        m.BuyBill.WaitMoney = m.BuyBill.WaitMoney + m.Money;

                        if (m.BuyBill.PayedMoney == 0)
                            m.BuyBill.PayState = PayStateEnum.NoPayed;
                        else if (m.BuyBill.WaitMoney<0 && m.BuyBill.PayedMoney<0)
                            m.BuyBill.PayState = PayStateEnum.HalfPayed;
                        else
                            throw new Exception("单据[" + m.BuyBill.Code + "]的金额超过应支付的总金额");
                    }
                }

                if (entity.BuyAdvanceMoney != null)
                {
                    entity.BuyAdvanceMoney.UsedMoney = entity.BuyAdvanceMoney.UsedMoney + entity.AdvanceMoney;
                }

                Update(entity);

                return scope.SaveChanges() > 0 ? new OperationResult(OperationResultType.Success, $"撤销审核1条记录!") : new OperationResult(OperationResultType.NoChanged);
            }
        }

        public StatementDetailItem EntityChange(BuyStatementDetail m)
        {
            var ItemEntity = new StatementDetailItem();
            ItemEntity.Id = m.Id.ToString();
            ItemEntity.Code = m.BuyBill.Code;
            ItemEntity.Name = m.Name;
            ItemEntity.BillId = m.BuyBillId.ToString();
            ItemEntity.NeedDate = m.BuyBill.NeedPayDate;
            ItemEntity.CreatedDate = m.BuyBill.CreateDate;
            ItemEntity.Money = m.BuyBill.Money;
            ItemEntity.PayedMoney = m.BuyBill.PayedMoney;
            ItemEntity.WaitMoney = m.BuyBill.WaitMoney;
            ItemEntity.thisPayMoney = m.BuyBill.WaitMoney;
            ItemEntity.thisPayedLastMonoey = 0;
            return ItemEntity;
        }
    }
}
